// pages/publish/index.js
var app = getApp()
var time= require("../../utils/util.js");

//获取当前时间戳  
var timestamp = Date.parse(new Date());  
timestamp = timestamp / 1000;  
// console.log("当前时间戳为：" + timestamp);  

//时间戳转为日期
let dataTime = time.formatTimeTwo(timestamp,'Y-M-D')
// console.log(time.formatTimeTwo(timestamp,'Y-M-D'))
// 日期转为时间戳
// let date = '2021-4-30';
// var repTime = date.replace(/-/g, '/');
// // console.log('当前时间为：',repTime)
// var timeTamp = Date.parse(repTime) / 1000;
// console.log('时间戳为：',timeTamp)

// //时间戳转为日期
// let dataTime = time.formatTimeTwo(timeTamp,'Y/M/D')
// console.log(time.formatTimeTwo(timeTamp,'Y/M/D'))
Page({
  /**
   * 页面的初始数据
   * 2021-04-24
   */
  data: {
    nowDate:dataTime,
    startDate: dataTime,//起始时间
    endDate:dataTime,//结束时间
    imgbox: [], //选择的图片的临时路径
    fileIDs: ['cloud://cloud1-2guh9tam1ee71336.636c-cloud1-2guh9tam1ee71336-1305678983/imgs/custom/custom1.jpg'], //上传云存储后的返回值
    enclosureTmp:'',//选择附件的临时位置
    enclosureCloudUrl:'',//选择附件的临时位置返回附件cloudurl
    customCover:true, //自定义封面是否隐藏
    fileName:'',//文件名
    fileSize:null, //文件大小
    items: [
      { name: 'cover1', value: '默认封面1' },
      { name: 'cover2', value: '默认封面2', checked: 'true'},
      { name: 'cover3', value: '默认封面3' },
      { name: 'customCover', value: '自定义' }
    ],
    radioValue:'',
    defaultShow:false, //默认封面框是否显示
    defaultImg:'cloud://cloud1-2guh9tam1ee71336.636c-cloud1-2guh9tam1ee71336-1305678983/imgs/custom/custom2.jpg',//图片路径
  },
  //-------------------------------------------选择时间开始--------------
  //起始时间调用方法
  bindDateChangeStart: function (e) {
    // console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      startDate: e.detail.value
    })
  },
  //结束时间调用方法
  bindDateChangeEnd: function (e) {
    // console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      endDate: e.detail.value
    })
  },
//单选框
  radioChange: function (e) {
    this.setData({
      fileIDs:[],
    })
    // console.log('radio发生change事件，携带value值为：', e.detail.value)
    this.setData({
      radioValue:e.detail.value,
    })
    // console.log('radio选择的value值为：', this.data.radioValue)
    if(e.detail.value=='customCover'){
      this.setData({
        customCover:false,
        defaultShow:true,
        defaultImg:'',
      })
    }else {
      this.setData({
        customCover:true,
      })
       // 设置默认图片
       let fileIDs = []
       console.log('e.detail.value',e.detail.value)
       console.log('customCover',this.data.customCover)
      if(e.detail.value=='cover1'){
        fileIDs.push('cloud://cloud1-2guh9tam1ee71336.636c-cloud1-2guh9tam1ee71336-1305678983/imgs/custom/custom1.jpg')
        this.setData({
          defaultShow:false,
          defaultImg:'cloud://cloud1-2guh9tam1ee71336.636c-cloud1-2guh9tam1ee71336-1305678983/imgs/custom/custom1.jpg',
          fileIDs:fileIDs,
        })


      }else if(e.detail.value=='cover2'){
        fileIDs.push('cloud://cloud1-2guh9tam1ee71336.636c-cloud1-2guh9tam1ee71336-1305678983/imgs/custom/custom2.jpg')
        this.setData({
          defaultShow:false,
          defaultImg:'cloud://cloud1-2guh9tam1ee71336.636c-cloud1-2guh9tam1ee71336-1305678983/imgs/custom/custom2.jpg',
          fileIDs:fileIDs,
        })
      }else if(e.detail.value=='cover3'){
        fileIDs.push('cloud://cloud1-2guh9tam1ee71336.636c-cloud1-2guh9tam1ee71336-1305678983/imgs/custom/custom3.jpg')
        this.setData({
          defaultShow:false,
          defaultImg:'cloud://cloud1-2guh9tam1ee71336.636c-cloud1-2guh9tam1ee71336-1305678983/imgs/custom/custom3.jpg',
          fileIDs:fileIDs,
        })
      }else{
        
      }
      console.log('url',this.data.fileIDs)
    }
  },
  //-------------------------------------------选择时间结束--------------

 //-------------------------------------------选择图片开始--------------
// 删除照片 &&
imgDelete1: function(e) {
  let that = this;
  let index = e.currentTarget.dataset.deindex;
  let imgbox = this.data.imgbox;
  imgbox.splice(index, 1)
  that.setData({
    imgbox: imgbox
  });
  // console.log('imgbox',that.data.imgbox)
},
//----------------------- 选择图片开始--------------------
addPic1: function(e) {
  var imgbox = this.data.imgbox;
  var that = this;
  var n = 5;
  if (5 > imgbox.length > 0) {
    n = 5 - imgbox.length;
  } else if (imgbox.length == 5) {
    n = 1;
  }
  wx.chooseImage({
    count: 1, //设置一次能选多少张图片
    sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
    sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
    success: function(res) {
      // console.log('tempFilePaths',res.tempFilePaths)
      // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
      var tempFilePaths = res.tempFilePaths
      if(imgbox.length+tempFilePaths.length<5){
        imgbox = imgbox.concat(tempFilePaths);
      }
      that.setData({
        imgbox: imgbox
      });
      console.log('imgbox',that.data.imgbox)
    }
  })
},
//----------------------- 选择图片结束--------------------

 //-----------------------------------------选择附件开始----------------
  //选择附件
  chooseEnclosure:function(e){
    var that = this;
    wx.chooseMessageFile({
      count: 1,  //能选择文件的数量
      type: 'file', //能选择文件的类型,我这里只允许上传文件.还有视频,图片,或者都可以
      success(res) { 
        // console.log('文件res',res)
        var size = res.tempFiles[0].size;
        var filename = res.tempFiles[0].path;
        var newfilename = filename + ""; 
        let ext = newfilename.substr(newfilename.lastIndexOf(".")).replace('.', ''); //获取文件名后缀
        // console.log(ext)
        if (size > 4194304||(ext!='docx'&&ext!='pdf'&&ext!='doc')){ //限制了文件的大小和具体文件类型 )
          wx.showToast({
          title: '文件大小不能超过4MB,格式必须为pdf、docx、doc！',
          icon: "none",
          duration: 2000,
          mask: true
          })
        }else{
          that.setData({
            enclosureTmp: res.tempFiles[0].path, //将文件的路径保存在页面的变量上,方便 wx.uploadFile调用
            fileName:res.tempFiles[0].name, //回显文件名
          })
          console.log('enclosureTmp',that.data.enclosureTmp)
        }
      }
    })
  },
//-----------------------------------------选择附件结束----------------


// 设置时间，将开始时间结束时间转换为时间戳

changeTime:function(time){
  // 日期转为时间戳
  var repTime = time.replace(/-/g, '/');
  // console.log('当前时间为：',repTime)
  var timeTamp = Date.parse(repTime) / 1000;
  // console.log('时间戳为：',timeTamp)
  return timeTamp;
},


isTelephone:function(telephone){
  // console.log('电话号码为',telephone)
  var mobile = /^[1][3,4,5,7,8][0-9]{9}$/;
  return mobile.exec(telephone);
},
//--------------------------提交招募开始---------------

formSubmit:function(e){
  let that = this
  let startDate = this.data.startDate
  let endDate = this.data.endDate
  
  let startDateSJC = this.changeTime(startDate)
  let endDateSJC = this.changeTime(endDate)
  // console.log("判断时间戳的数据类型",typeof startDateSJC)
    //获取基础表单数据

    console.log (e.detail.value.recruitName)
    console.log('附件是否为空',this.data.enclosureTmp)
    // 获取最近一次发布的时间
    const releaseTime = wx.getStorageSync('releaseTime')
    if((Date.parse(new Date())/1000-releaseTime<30000)&&!(wx.getStorageSync('openid')=='o38Et46UY5nALhTPJQ9-WyC8dExU')){   //添加白名单  可以连续发
      console.log('两次发布时间差',Date.parse(new Date())/1000-releaseTime)
      wx.showToast({
        icon: 'none',
        title: '你已经发布过一次啦，请稍后再来！'
      });
    }else if (e.detail.value.recruitName==='') {
      wx.showToast({
        icon: 'none',
        title: '招募名称不能为空'
      });
    }else if (e.detail.value.recruitIntroduce===''){
      wx.showToast({
        icon: 'none',
        title: '招募简介不能为空'
      });
    }else if (endDateSJC<=startDateSJC){
      wx.showToast({
        icon: 'none',
        title: '结束时间必须大于开始时间'
      });
    }else if (e.detail.value.recruitNumber===''){
      wx.showToast({
        icon: 'none',
        title: '招募人数不能为空'
      });
    }else if(this.data.radioValue==='customCover'&& !this.data.imgbox.length) {
      wx.showToast({
        icon: 'none',
        title: '图片类容为空'
      });
    }else if (e.detail.value.personLiable===''){
      wx.showToast({
        icon: 'none',
        title: '联系人不能为空'
      });
    }else if (e.detail.value.telephone===''){
      wx.showToast({
        icon: 'none',
        title: '联系号码不能为空'
      });
    }else if (!this.isTelephone(e.detail.value.telephone)){
      wx.showToast({
        icon: 'none',
        title: '联系电话输入格式不对'
      });
    }
    // else if (this.data.enclosureTmp==''){
    //   wx.showToast({
    //     icon: 'none',
    //     title: '附件不能为空'
    //   });
    // }
    else{
        //上传图片到云存储
        wx.showLoading({
          title: '上传中',
        })
        let promiseArr = [];
        //上传图片
        console.log('是否自定义',this.data.customCover)
        console.log('图片url',this.data.fileIDs)
        if (!this.data.customCover) {  //判断是否需要上传图片
           //重置fileIDs,防止上传之前的图片
           that.setData({
            fileIDs:[],
          })
          for (let i = 0; i < this.data.imgbox.length; i++) {
            promiseArr.push(new Promise((reslove, reject) => {
              let item = this.data.imgbox[i];
              let suffix = /\.\w+$/.exec(item)[0]; //正则表达式返回文件的扩展名
              var that = this
              var timestamp = Date.parse(new Date());
              wx.cloud.uploadFile({
                cloudPath:'imgs/recruitImgs/'+timestamp+i+suffix,
                filePath:item,
                success:res=>{
                  that.setData({
                    fileIDs: that.data.fileIDs.concat(res.fileID)
                  });
                  reslove();
                },
                fail(err){
                  console.log(res)
                  reject();
                }
              })
            }));
          }
        }
        //上传附件
        promiseArr.push(new Promise((reslove, reject) => {
          let enclosureTmp = this.data.enclosureTmp;
          let suffix = /\.\w+$/.exec(enclosureTmp)[0]; //正则表达式返回文件的扩展名
          var that = this
          var timestamp = Date.parse(new Date());
          wx.cloud.uploadFile({
            cloudPath:'file/enclosure/'+timestamp+suffix,
            filePath:enclosureTmp,
            success:res=>{
              that.setData({
                enclosureCloudUrl: res.fileID
              });
              console.log(that.data.enclosureCloudUrl) //输出上传后图片的返回地址
              reslove();
            },
            fail(err){
              console.log(res)
              reject()
            }
          })
        }));
        Promise.all(promiseArr).then(res => { //等数组都做完后做then方法
          wx.cloud.callFunction({
            name:'addRecruit',
            data:{
              recruitName : e.detail.value.recruitName,
              recruitIntroduce:e.detail.value.recruitIntroduce,
              startTime:startDateSJC,
              endTime:endDateSJC,
              recruitNumber:e.detail.value.recruitNumber,
              imgs:this.data.fileIDs,
              personLiable:e.detail.value.personLiable,
              telephone:e.detail.value.telephone,
              // recruitState:2,
              enclosureUrl:that.data.enclosureCloudUrl,
              // recruitClassId:null,
              // userId: wxContext.OPENID,
            }
            ,
            success: res => {
              // wx.hideLoading()
              wx.showToast({
                duration:2000,
                icon:'success',
                title: '提交成功,请耐心等待审核结果',
              })
              console.log('发布成功', res)
              // 发布成功后要设置一个时间，不给用户一直发布
              wx.setStorageSync('releaseTime',Date.parse(new Date())/1000)
            },
            fail: err => {
              // wx.hideLoading()
              wx.showToast({
                duration:2500,
                icon: 'none',
                title: '网络不给力....'
              })
              console.error('发布失败', err)
              //发布失败后，删除之前上传的垃圾文件。
              
            }
          }) 
        }).catch(err=>{
          console.log(err)
        })  
    }
   },
  
 //--------------------------提交招募结束---------------

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    // 判断是否登录
    if(wx.getStorageSync('login')){  
      
    }else{
      wx.showModal({
        title: '提示',
        content: '请先登录',
        success (res) {
          if (res.confirm) {
            if(app.globalData.canIUseGetUserProfile){
              app.getUserProfile(1)
            }else{
              app.getUserInfo(1)
            }
          } else if (res.cancel) {
            console.log('用户点击取消')
            wx.switchTab({
              url: '/pages/personal/index',
            })
          }
        }
      })
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
})
